﻿using System;  
using System.Reflection;
using UnityEditor; 

namespace XFGameFramework
{
    public class ListenerFileChange : UnityEditor.AssetModificationProcessor
    {

        public static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions option)
        { 
             
            if (assetPath.StartsWith("Assets/Resources/XFGameFramework") && !assetPath.StartsWith( "Assets/Resources/XFGameFramework/Scripts"))
            {
                // Assets/Resources/XFABManagerSettings.asset
                EditorUtility.DisplayDialog("提示",string.Format("文件:{0} 是XFGameFramework所需要的文件,不能删除!否则会影响XFGameFramework的正常使用!",assetPath), "确定");
                return AssetDeleteResult.FailedDelete;
            }
            else
                return AssetDeleteResult.DidNotDelete;

        }

        
 

        private static bool opening = false;

        /// <summary>
        /// 获取当前日志窗口选中的日志的堆栈信息
        /// </summary>
        /// <returns></returns>
        private static string GetStackTrace()
        {
            var consoleWindowType = typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");

            //获取窗口实例
            var fileInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
            var consoleIns = fileInfo?.GetValue(null);
            if (consoleIns == null) return null;
            if (EditorWindow.focusedWindow == (EditorWindow)consoleIns)
            {
                fileInfo = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
                var activeText = fileInfo?.GetValue(consoleIns).ToString();
                return activeText;
            }

            return null;
        }

        [UnityEditor.Callbacks.OnOpenAsset()]
        private static bool OnOpenAsset(int insId, int line)
        {
            if (opening) return false;


            UnityEngine.Object obj = EditorUtility.InstanceIDToObject(insId);
            var stackTrace = GetStackTrace();  

            if (string.IsNullOrEmpty(stackTrace)) return false;

            if (obj.name == "LogUtil" && obj.GetType() == typeof(MonoScript))
            {
                var matches = System.Text.RegularExpressions.Regex.Match(stackTrace, @"\(at (.+)\)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                var pathLine = "";
                while (matches.Success)
                {
                    pathLine = matches.Groups[1].Value;
                    if (!pathLine.Contains("/LogUtil.cs"))
                    {
                        var splitIndex = pathLine.LastIndexOf(":");
                        var path = pathLine.Substring(0, splitIndex);
                        line = Convert.ToInt32(pathLine.Substring(splitIndex + 1));
                        //UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(p, line);
                        opening = true;
                        AssetDatabase.OpenAsset(AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path), line);
                        opening = false;
                        return true;
                    }

                    matches = matches.NextMatch();
                }
            }

            return false;
        }  
    }
}


